#!/usr/bin/env python

from os.path import abspath
from optparse import OptionParser
from subprocess import Popen
from tempfile import NamedTemporaryFile

script = \
"""
setmode -bs

setcable -port usb{0}
identify -inferir
identifyMPM

assignfile -p 1 -file "{1}"
program -p 1

quit
"""


usage = \
"""
csb-impact.py [opts] file.bit

Run `impact -batch' on a script generated from the supplied bit file and 
the supplied options.
"""

op = OptionParser(usage=usage)
op.add_option("-u", dest='usb', default=22, type="int",
              help="Specify USB port to write to", metavar='PORT')

opts, args = op.parse_args()

if len(args) == 0:
    msg = "Please supply a bit file.\n"
    msg += "See `csb-impact.py -h' for more.\n"
    sys.stderr.write(msg)
    sys.exit(-101)

bitfile = abspath(args[0])
              
with NamedTemporaryFile(suffix='.scr') as tmpfile:
    tmpfile.write(script.format(opts.usb, bitfile))
    tmpfile.flush()

    cmdargs = "impact -batch {0}".format(tmpfile.name)
    pipe = Popen(cmdargs.split())
    
    pipe.communicate()



